import json
import uuid
from django.http import JsonResponse, HttpResponseRedirect
from django.shortcuts import render
from django.views import View
from reservation.models import Reservation
from cars.models import *
from order.models import Order
from newenergy.settings import alipay
import datetime as datatime
# Create your views here.
import random


#预约列表
class ReservationView(View):
    def get(self, request):
        #获取用户下的车辆信息
        user = request.session.get('user')

        #获取预约列表
        reservation_list = Reservation.objects.filter(user_id=user.id)
        number = len(reservation_list)
        return render(request, 'templates/reservation/reservation.html', {'reservation_list':reservation_list, 'number':number})


#添加预约
class Add_ReserationView(View):
    def get(self, request, car_id):
        #获取当前车辆的相关信息
        user = request.session.get('user')
        car = Cars.objects.get(id=car_id)
        model = Carmodels.objects.get(id=car.model_id)
        type = Cartype.objects.get(id=car.type_id)
        detail = Cardetails.objects.get(car_id=car_id)
        #检查这辆车是否存在
        if Reservation.objects.filter(cars_id=car_id).exists():
            return JsonResponse({'message':'已预约，请勿重复预约!'})
        else:
            # 如果不存在就插入预约数据库中
            Reservation.objects.create(img=car.durl,
                                       cname=car.cname,
                                       model=model.mname,
                                       type=type.type_name,
                                       firm=detail.firm,
                                       price=detail.payment,
                                       oprice=car.price,
                                       rank=detail.rank,
                                       endurance=detail.endurance,
                                       charge=detail.charge,
                                       cars_id=car.id,
                                       user_id=user.id)
        return JsonResponse({'message':'预约成功!'})


#删除预约
class Delete(View):
    def post(self,request):
        reservation_id = request.POST.get('reservation_id','')
        print(reservation_id)
        if reservation_id:
            try:
                reservation = Reservation.objects.get(cars_id=reservation_id)
                reservation.delete()
                # 返回响应，比如重定向到某个页面或返回JSON响应
                return JsonResponse({'message': '预约已删除!'}, status=200)
            except Reservation.DoesNotExist:
                # 如果找不到reservation，返回错误响应
                return JsonResponse({'error': '没有找到你要删除的车辆!'}, status=404)
        else:
            # 如果没有提供reservation_id，返回错误响应
            return JsonResponse({'error': '服务器错误!'}, status=400)
        return HttpResponseRedirect('/reservation/')


#批量删除
class Dall(View):
    def post(self,request):
        # 假设前端发送的是JSON格式的ID数组
        reservation_ids = request.body  # 原始请求体

        # 解析JSON数据
        reservation_ids = json.loads(reservation_ids)
        print(reservation_ids)
        # 确保接收到的是列表
        if isinstance(reservation_ids, list):
            # 验证并删除
            Reservation.objects.filter(id__in=reservation_ids).delete()
            return JsonResponse({'message': '删除成功！'}, status=200)

        return JsonResponse({'message': '删除失败！'}, status=200)


#购买
class Purchase(View):
    def post(self, request,):
        reservation_id = request.POST.get('reservation_id')
        print(reservation_id)
        reservation = Reservation.objects.get(cars_id=reservation_id)
        user = request.session.get('user')
        order_number = datatime.datetime.today().strftime('%Y%m%d%H%M%S')
        #生成订单
        Order.objects.create(model=reservation.model,
                             cname=reservation.cname,
                             img=reservation.img,
                             type=reservation.type,
                             price=reservation.price,
                             firm=reservation.firm,
                             charge=reservation.charge,
                             endurance=reservation.endurance,
                             rank=reservation.rank,
                             order_uuid=str(uuid.uuid4()),
                             order_number=order_number,
                             user_id=user.id,
                             cars_id=reservation_id
                             )

        total = reservation.price
        # 导入alipay对象,并调用统一收单下单并支付页面接口
        # 参考文档：https://opendocs.alipay.com/apis/api_1/alipay.trade.page.pay
        # python的uuid模块提供UUID类和函数uuid1(), uuid3(), uuid4(), uuid5() 来生成1, 3, 4, 5各个版本的UUID
        # 1基于时间戳；3基于名字的MD5散列值；4基于随机数；5基于名字的SHA-1散列值
        order_param = alipay.api_alipay_trade_page_pay(
            # 商户订单号
            # 由商家自定义，64个字符以内，仅支持字母、数字、下划线且需保证在商户端不重复。
            out_trade_no=str(uuid.uuid4()),
            # 订单总金额
            total_amount=total,
            # 订单标题
            # 注意：不可使用特殊字符，如 /，=，& 等。
            subject=user.name + '的' + reservation.cname,
            # 回调地址
            return_url='http://127.0.0.1:8000/order/checkbuy/' + reservation_id + '/'  # 当支付成功后，支付宝沙箱回调给服务端该url指向的get请求
            # return_url='http://593f047.r1.cpolar.top/goods/login/'
        )
        # 删除预约信息
        reservation.delete()
        # 拼接支付地址：支付宝网关 + 订单参数
        pay_url = 'https://openapi-sandbox.dl.alipaydev.com/gateway.do?' + order_param

        return JsonResponse({'url': pay_url}, status=200)


#去支付
class PayView(View):
    def post(self,request):
        reservation_id = request.POST.get('reservation_id')
        reservation = Order.objects.get(cars_id=reservation_id)
        user = request.session.get('user')
        #生成订单,如果订单不存在就创建
        total = reservation.price
        # 导入alipay对象,并调用统一收单下单并支付页面接口
        # 参考文档：https://opendocs.alipay.com/apis/api_1/alipay.trade.page.pay
        # python的uuid模块提供UUID类和函数uuid1(), uuid3(), uuid4(), uuid5() 来生成1, 3, 4, 5各个版本的UUID
        # 1基于时间戳；3基于名字的MD5散列值；4基于随机数；5基于名字的SHA-1散列值
        order_param = alipay.api_alipay_trade_page_pay(
            # 商户订单号
            # 由商家自定义，64个字符以内，仅支持字母、数字、下划线且需保证在商户端不重复。
            out_trade_no=str(uuid.uuid4()),
            # 订单总金额
            total_amount=total,
            # 订单标题
            # 注意：不可使用特殊字符，如 /，=，& 等。
            subject=user.name+'的'+reservation.cname,
            # 回调地址
            return_url='http://127.0.0.1:8000/order/checkbuy/' + reservation_id + '/'   # 当支付成功后，支付宝沙箱回调给服务端该url指向的get请求
            # return_url='http://593f047.r1.cpolar.top/goods/login/'
        )
        # 拼接支付地址：支付宝网关 + 订单参数
        pay_url = 'https://openapi-sandbox.dl.alipaydev.com/gateway.do?' + order_param


        return JsonResponse({'url': pay_url},status=200)



